<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
        <title>博客后台管理 - 文章管理</title>
        <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-touch-fullscreen" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="default">
        <link rel="stylesheet" type="text/css" href="./css/materialdesignicons.min.css">
        <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="./css/style.min.css">
        <link rel="stylesheet" href="./elementui/index.min.css">
        <style>
            /* v-cloak 隐藏未渲染的DOM */
            [v-cloak] {
                display: none;
            }
        </style>
    </head>

    <body>
        <div id="app">
            <el-row style="padding: 15px;">
                <el-card class="box-card">
                    <el-form ref="articleSearchForm" @submit.native.prevent :rules="articleSearchFormRules"
                        :model="articleSearchForm" label-width="80px">
                        <el-form-item label="文章标题" prop="title">
                            <el-input clearable v-model="articleSearchForm.title" clearable></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="small" @click="onArticleSearchFormSubmit">搜索</el-button>
                            <el-button size="small" @click="resetSearchForm()">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>

                <el-card class="box-card" style="margin-top: 15px;">
                    <el-button @click="deleteArticleBatch" type="danger" size="small"
                        style="margin-bottom: 5px;">批量删除</el-button>
                    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
                        <el-table-column align="center" type="selection" width="50">
                        </el-table-column>
                        <el-table-column align="center" prop="id" label="ID" width="80">
                        </el-table-column>
                        <el-table-column :fit="true" align="center" prop="title" label="标题">
                        </el-table-column>
                        <el-table-column align="center" prop="cate_name" label="分类" width="100">
                        </el-table-column>
                        <el-table-column align="center" prop="description" label="描述" width="300">
                        </el-table-column>
                        <el-table-column align="center" prop="created_at" label="创建时间" width="200">
                        </el-table-column>
                        <el-table-column align="center" fixed="right" label="操作" width="100">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="editArticle(scope.row.id)">编辑</el-button>
                                <el-button type="text" size="small" style="color: red;"
                                    @click="deleteArticle(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-pagination background layout="prev, pager, next" :page-sizes="[20, 30, 40, 50]"
                        :page-size="pageSize" :current-page="currentPage" :total="artTotalCount"
                        @current-change="onPageChange" @size-change="onPageSizeChange" style="margin-top: 15px">
                    </el-pagination>
                </el-card>
            </el-row>
        </div>

        <script type="text/javascript" src="./js/jquery.min.js"></script>
        <script type="text/javascript" src="./js/main.min.js"></script>
        <script src="./elementui/vue.min.js"></script>
        <script src="./elementui/index.min.js"></script>
        <script>
            new Vue({
                el: '#app',
                data: {
                    // 文章搜索表单
                    articleSearchForm: {
                        title: '',
                    },
                    // 文章搜索表单验证规则
                    articleSearchFormRules: {
                        title: [
                            { required: true, message: '请输入文章标题进行搜索', trigger: 'blur' },
                        ],
                    },
                    // 多选框选中数据
                    multipleSelection: [],
                    // 文章列表数据
                    tableData: [],
                    // 文章总数
                    artTotalCount: 0,
                    // 当前页码
                    currentPage: 1,
                    // 每页显示条数
                    pageSize: 20,
                },
                methods: {
                    // 文章搜索表单提交
                    onArticleSearchFormSubmit() {
                        if (this.articleSearchForm.title == '') return;

                        fetch(`http://127.0.0.1:5588/api/article/search?keyword=${this.articleSearchForm.title}`, {
                            method: "GET",
                        })
                            .then((response) => response.json())
                            .then(res => {
                                if (res.code != 200) {
                                    return this.$message.error(res.msg);
                                }

                                this.tableData = res.data;
                                this.artTotalCount = res.total;
                            })
                            .catch((err) => {
                                console.error("Error:", err);
                            });
                    },

                    // 文章搜索表单重置
                    resetSearchForm() {
                        if (this.articleSearchForm.title == '') return;

                        this.$refs.articleSearchForm.resetFields();
                        // 重新加载列表
                        this.getArticleList();
                    },

                    // 批量删除文章
                    deleteArticleBatch() {
                        if (!this.multipleSelection || this.multipleSelection.length === 0) {
                            return this.$message.warning('请选择要删除的文章');
                        }

                        this.$confirm('确定删除选中的文章吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            let ids = [];
                            this.multipleSelection.forEach(item => {
                                ids.push(item.id);
                            });

                            // 提交批量删除
                            fetch("http://127.0.0.1:5588/admin/articles/batchDelete", {
                                method: "POST",
                                headers: {
                                    "Authorization": sessionStorage.getItem('token') || '',
                                },
                                body: JSON.stringify({
                                    ids: ids,
                                }),
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error(res.msg);
                                    }

                                    this.$message.success('操作成功!');
                                    // 重新加载列表
                                    this.getArticleList();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });

                        })
                    },

                    // 多选框选择事件
                    handleSelectionChange(val) {
                        this.multipleSelection = val;
                    },

                    // 编辑文章
                    editArticle(id) {
                        // 打开编辑文章页面
                        parent.$(parent.document).data('multitabs').create({
                            iframe: true,
                            title: '写文章',
                            url: `lyear_write_article.html?aid=${id}`
                        }, true);
                    },

                    // 行删除文章
                    deleteArticle(id) {
                        this.$confirm('确定删除该文章吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            // 提交删除
                            fetch(`http://127.0.0.1:5588/admin/articles/${id}`, {
                                method: "DELETE",
                                headers: {
                                    "Authorization": sessionStorage.getItem('token') || '',
                                }
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error(res.msg);
                                    }

                                    this.$message.success('操作成功!');
                                    // 重新加载列表
                                    this.getArticleList();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });
                        })
                    },

                    // 每页显示条数改变
                    onPageSizeChange(pageSize) {
                        this.pageSize = pageSize;
                        this.onPageChange(this.currentPage);
                    },

                    // 翻页
                    onPageChange(pageNum) {
                        this.currentPage = pageNum; // 更新当前页码
                        fetch(`http://127.0.0.1:5588/admin/articles?pageNum=${pageNum}&pageSize=${this.pageSize}`, {
                            method: "GET",
                            headers: {
                                "Authorization": sessionStorage.getItem('token') || '',
                            },
                        })
                            .then((response) => response.json())
                            .then(res => {
                                if (res.code != 200) {
                                    return this.$message.error(res.msg);
                                }

                                this.tableData = res.data;
                                this.artTotalCount = res.total;
                            })
                            .catch((err) => {
                                console.error("Error:", err);
                            });
                    },

                    // 获取文章列表
                    getArticleList() {
                        fetch(`http://127.0.0.1:5588/admin/articles?pageNum=1&pageSize=20`, {
                            method: "GET",
                            headers: {
                                "Authorization": sessionStorage.getItem('token') || '',
                            },
                        })
                            .then((response) => response.json())
                            .then(res => {
                                if (res.code != 200) {
                                    return this.$message.error(res.msg);
                                }

                                this.tableData = res.data;
                                this.artTotalCount = res.total;
                            })
                            .catch((err) => {
                                console.error("Error:", err);
                            });
                    }
                },
                mounted() {
                    // 获取文章列表
                    this.getArticleList();
                }
            });
        </script>
    </body>

</html>